package main

import (
	"context"
	"fmt"
	"go_stu/5_grpc_stu/4_stream_grpc_test/protos"
	"sync"
	"time"

	"google.golang.org/grpc"
)

func main() {
	conn, err := grpc.Dial("localhost:50052", grpc.WithInsecure())
	if err != nil {
		panic(err.Error())
	}
	defer conn.Close()
	// 服务端流模式
	c := protos.NewGreaterClient(conn)
	/*res, err := c.GetStream(context.Background(), &protos.StreamReqData{Data: "hello"})
	if err != nil {
		panic(err.Error())
	}
	for {
		a, err := res.Recv()
		if err != nil {
			panic(err.Error())
		}
		fmt.Println(a.Data)
	}*/

	// 客户端流模式
	/*putS, err := c.PutStream(context.Background())
	if err != nil {
		panic(err.Error())
	}
	i := 0
	for {
		i++
		putS.Send(&protos.StreamReqData{
			Data: fmt.Sprintf("mooc%d", i),
		})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}*/
	// 客户端双向流
	req, _ := c.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := req.Recv()
			fmt.Println("收到：" + data.Data)
		}
	}()
	go func() {
		defer wg.Done()
		for {
			_ = req.Send(&protos.StreamReqData{Data: "我是客户端"})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
}
